package com.holly.unit.deform.modular.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.holly.unit.auth.api.context.LoginContext;
import com.holly.unit.auth.api.pojo.login.LoginUser;
import com.holly.unit.core.pojo.response.ErrorResponseData;
import com.holly.unit.core.pojo.response.ResponseData;
import com.holly.unit.core.pojo.response.SuccessResponseData;
import com.holly.unit.db.api.factory.PageResultFactory;
import com.holly.unit.db.api.pojo.page.PageResult;
import com.holly.unit.deform.api.DeformAuthApi;
import com.holly.unit.deform.api.DeformBaseInfoApi;
import com.holly.unit.deform.api.DeformDataApi;
import com.holly.unit.deform.api.constants.DeformConstants;
import com.holly.unit.deform.api.pojo.base.DesignFormDTO;
import com.holly.unit.deform.api.pojo.base.DictModelDTO;
import com.holly.unit.deform.api.pojo.base.TranslateDataDTO;
import com.holly.unit.deform.api.pojo.data.DesignFormDataDTO;
import com.holly.unit.deform.entity.DesignForm;
import com.holly.unit.deform.modular.pojo.*;
import com.holly.unit.scanner.api.annotation.ApiResource;
import com.holly.unit.scanner.api.annotation.GetResource;
import com.holly.unit.scanner.api.annotation.PostResource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 类描述: 表单设计控制器
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/4/7 16:21
 */
@Slf4j
@RestController
@ApiResource(name = "表单设计")
@Api(tags = "表单设计")
public class DeformBaseInfoController {

    @Resource
    private DeformBaseInfoApi api;

    @Resource
    private DeformAuthApi auth;

    @Resource
    private DeformDataApi data;

    /**
     * 分页列表查询
     *
     * @param designFormRequest
     * @return
     */
    @ApiOperation(value = "分页列表查询" ,notes = "分页列表查询")
    @GetResource(name = "分页列表查询" , path = "/designForm/queryPageList")
    public ResponseData queryPageList(DesignFormRequest designFormRequest,HttpServletRequest req) {
        // 参数处理
        designFormRequest.setParam(req.getParameterMap());
        QueryWrapper<DesignForm> queryWrapper =designFormRequest.handleQueryWrapper();
        boolean hasParentId = designFormRequest.hasParentId();

        // 传入了父ID，表明是子表
        if (hasParentId) {
            // 子表直接查询所有，不分页
            List<DesignFormDTO> designFormList = api.fetchList(queryWrapper);
            // 把DesignFormDTO   to   DesignFormPage
            List<DesignFormPage> viewDatas = dto2Page(designFormList);

            // 把List 转化成 Resords 前端使用的是Page中record这个字段【前端重构代码要修改】
            PageResult<DesignFormPage> ans = PageResultFactory.createPageResult(viewDatas,0L,
                    designFormRequest.getPageSize(),
                    designFormRequest.getPageNo());
            return new SuccessResponseData(ans);
        } else {
            queryWrapper.isNull("parent_id");
            PageResult<DesignFormDTO> dtos = api.pageList(queryWrapper);
            PageResult<DesignFormPage> res = createPageResult(hasParentId,dtos);
            return  new SuccessResponseData(res);
        }
    }

    @ApiOperation(value = "新增" ,notes = "新增")
    @PostResource(name = "新增" , path = "/designForm/add")
    public ResponseData add(@RequestBody DesignFormRequest designFormRequest) {
        DesignFormDTO designFormDTO = new DesignFormDTO();
        BeanUtil.copyProperties(designFormRequest, designFormDTO);
        //获取登录人
        LoginUser loginUser = LoginContext.me().getLoginUser();
        designFormDTO.setCreateUser(loginUser.getUserId());
        if(designFormDTO!=null && designFormDTO.getDesformDesignJson()!=null){
            designFormDTO.setDesformDesignJson(HtmlUtils.htmlUnescape(designFormDTO.getDesformDesignJson()));
        }
        api.saveOneToMany(designFormDTO);
        return new SuccessResponseData() ;
    }

    /**
     * 编辑
     *
     * @param designFormRequest
     * @return
     */
    @ApiOperation(value = "编辑" ,notes = "编辑")
    @PostResource(name = "编辑" , path = "/designForm/edit")
    public ResponseData edit(@RequestBody DesignFormRequest designFormRequest) {
        DesignForm designForm = new DesignForm();
        BeanUtil.copyProperties(designFormRequest, designForm);
        DesignFormDTO designFormEntity = api.getById(designForm.getId());
        String desformCode = designFormEntity.getDesformCode();
        //设计表单保存
        if(designForm!=null && designForm.getDesformDesignJson()!=null){
            designForm.setDesformDesignJson(HtmlUtils.htmlUnescape(designForm.getDesformDesignJson()));
            designForm.setType(designFormEntity.getType());
            designForm.setDesformCode(designFormEntity.getDesformCode());
            designForm.setCgformCode(designFormEntity.getCgformCode());
            designForm.setDesformName(designFormEntity.getDesformName());
        }
        api.updateById(designForm);
        //修改默认移动视图逻辑
        if (DeformConstants.IS_MOBILE_VIEW_Y.equals(designForm.getIzMobileView())) {
            String parentCode = designFormEntity.getDesformCode();
            if (DeformConstants.DEFORM_TYPE_SV.equals(designFormEntity.getDesformType())) {
                parentCode = designFormEntity.getParentCode();
            }
            api.setMobileView(parentCode, desformCode);
        }
        return new SuccessResponseData();
    }

    /**
     * 通过id删除
     *
     * @param designFormDelRequest
     * @return
     */
    @ApiOperation(value = "通过id删除" ,notes = "通过id删除")
    @PostResource(name = "通过id删除" , path = "/designForm/delete")
    public ResponseData delete(@RequestBody @Validated(DesignFormDelRequest.delById.class) DesignFormDelRequest designFormDelRequest) {
        String id = designFormDelRequest.getId();
        api.delOneToMany(id);
        return new SuccessResponseData();
    }

    /**
     * 批量删除
     *
     * @param designFormDelRequest
     * @return
     */
    @ApiOperation(value = "批量删除" ,notes = "批量删除")
    @GetResource(name = "批量删除" , path = "/designForm/deleteBatch")
    public ResponseData deleteBatch(@Validated(DesignFormDelRequest.delByIds.class) DesignFormDelRequest designFormDelRequest) {
        String ids = designFormDelRequest.getIds();
        api.delBatchOneToMany(Arrays.asList(ids.split(",")));
        return new SuccessResponseData();
    }

    /**
     * 通过 code 查询
     *
     * @param designFormQueryByCodeRequest
     * @return
     */
    @ApiOperation(value = "code查询" ,notes = "code查询")
    @GetResource(name = "code查询" , path = "/designForm/queryByCode")
    public ResponseData queryByCode(@Validated(DesignFormQueryByCodeRequest.queryByCode.class) DesignFormQueryByCodeRequest designFormQueryByCodeRequest) {
        String desformCode = designFormQueryByCodeRequest.getDesformCode();
        DesignFormDTO designForm = api.getByCode(desformCode);
        return new SuccessResponseData(api.queryAllDictItem(designForm));
    }

    /**
     * 查询列，同时查询按钮权限
     * @param designFormQueryByCodeRequest
     * @param
     * @return
     */
    @ApiOperation(value = "查询列按钮权限" ,notes = "查询列按钮权限")
    @GetResource(name = "查询列按钮权限" , path = "/designForm/getColumns")
    public ResponseData getColumns(@Validated(DesignFormQueryByCodeRequest.queryByCode.class) DesignFormQueryByCodeRequest designFormQueryByCodeRequest) {
        ResponseData result = queryByCode(designFormQueryByCodeRequest);
        if (result.getSuccess()) {
            // 查询按钮权限
            LoginUser loginUser = LoginContext.me().getLoginUser();
            JSONObject buttonsAuth = auth.fetchButtonsAuth(designFormQueryByCodeRequest.getDesformCode(), loginUser.getAccount());
            // 封装返回对象
            JSONObject res = new JSONObject();
            res.put("designForm", result.getData());
            res.put("buttonsAuth", buttonsAuth);
            return new SuccessResponseData(res);
        }
        return result;
    }

    /**
     * 翻译列数据
     */
    @ApiOperation(value = "翻译列数据" ,notes = "翻译列数据")
    @PostResource(name = "翻译列数据" , path = "/designForm/translateColumns")
    public ResponseData translateColumns(@RequestBody List<TranslateDataDTO> translateDataList) {
        if (translateDataList != null) {
            Map<String, List<DictModelDTO>> translateObject = api.translateColumns(translateDataList);
            return new SuccessResponseData(translateObject);
        }
        return new ErrorResponseData("101","translateDataList不能为空");
    }

    /**
     * 通过id查询
     *
     * @param designFormQueryByIdRequest
     * @return
     */
    @ApiOperation(value = "通过id查询" ,notes = "通过id查询")
    @GetResource(name = "通过id查询" , path = "/designForm/queryById")
    public ResponseData queryById(@Validated(DesignFormQueryByIdRequest.queryById.class) DesignFormQueryByIdRequest designFormQueryByIdRequest) {
        DesignFormDTO designForm = api.getById(designFormQueryByIdRequest.getId());
        return new SuccessResponseData(api.queryAllDictItem(designForm));
    }

    /**
     * 通过id查询
     *
     * @param designFormQueryByIdRequest
     * @return
     */
    @ApiOperation(value = "通过id查询" ,notes = "通过id查询")
    @GetResource(name = "通过id查询" , path = "/designForm/queryDesignFormDataByMainId")
    public ResponseData queryDesignFormDataListByMainId(@Validated(DesignFormQueryByIdRequest.queryById.class) DesignFormQueryByIdRequest designFormQueryByIdRequest) {
        List<DesignFormDataDTO> designFormDataList = data.selectByMainId(designFormQueryByIdRequest.getId());
        return new SuccessResponseData(designFormDataList);
    }

    /**
     * 同步索引
     */
    @ApiOperation(value = "同步索引" ,notes = "同步索引")
    @PostResource(name = "同步索引" , path = "/designForm/redoAllIndex")
    public ResponseData redoAllIndex(@RequestBody JSONObject formData) {
        String rowIds  = StrUtil.isEmptyIfStr(formData.get("selections"))?"":formData.get("selections").toString().trim();
        // 同步索引
        api.redoAllIndex(rowIds);
        return new SuccessResponseData();
    }

    /**
     * 强制同步索引
     */
    @ApiOperation(value = "强制同步索引" ,notes = "强制同步索引")
    @PostResource(name = "强制同步索引" , path = "/designForm/redoAllIndexForce")
    public ResponseData redoAllIndexForce(@RequestBody JSONObject formData) {
        String rowIds  = StrUtil.isEmptyIfStr(formData.get("selections"))?"":formData.get("selections").toString().trim();
        api.redoAllIndexForce(rowIds);
        return new SuccessResponseData();
    }

    /***************************************************内部工具类*****************************************************/
    private List<DesignFormPage> dto2Page(List<DesignFormDTO> designFormList) {
        List<DesignFormPage> res = new ArrayList<>();
        designFormList.stream().forEach(entity->{
            DesignFormPage page = new DesignFormPage();
            BeanUtil.copyProperties(entity,page);
            res.add(page);
        });
        return res;
    }


    private PageResult<DesignFormPage> createPageResult(boolean hasParentId,PageResult<DesignFormDTO> designFormDTOPageResult) {

        List<DesignFormPage> list = new ArrayList<>();
        PageResult<DesignFormPage> res = new PageResult<>();
        List<DesignFormDTO> rows = designFormDTOPageResult.getRows();

        rows.stream().forEach(record->{
            DesignFormPage designFormPage = new DesignFormPage();
            BeanUtil.copyProperties(record, designFormPage);
            // 最多两个层级
            designFormPage.setHasChildren(hasParentId?false:api.hasChild(record.getId()));
            list.add(designFormPage);
        });

        res.setRows(list);
        res.setTotalRows(Convert.toInt(designFormDTOPageResult.getTotalRows()));
        res.setPageNo(designFormDTOPageResult.getPageNo());
        res.setPageSize(designFormDTOPageResult.getPageSize());
        res.setTotalPage(PageUtil.totalPage(designFormDTOPageResult.getTotalRows(), designFormDTOPageResult.getPageSize()));
        return res;
    }

    /**
     * 分页列表查询
     *
     * @param designFormRequest
     * @return
     */
    @ApiOperation(value = "列表查询" ,notes = "列表查询")
    @GetResource(name = "列表查询" , path = "/designForm/queryList")
    public ResponseData queryList(DesignFormRequest designFormRequest,HttpServletRequest req) {
        // 参数处理
        QueryWrapper<DesignForm> queryWrapper =designFormRequest.handleQueryWrapper();
        List<DesignFormDTO> designFormList = api.fetchList(queryWrapper);
        return new SuccessResponseData(designFormList);
    }

    /**
     * 查询code是否存在
     * @param designFormDTO
     * @return
     */
    @ApiOperation(value = "code查询" ,notes = "code查询")
    @GetResource(name = "code查询" , path = "/designForm/checkCode")
    public ResponseData check(@Validated(DesignFormQueryByCodeRequest.queryByCode.class) DesignFormDTO designFormDTO) {
        return new SuccessResponseData( api.checkCode(designFormDTO));
    }
}
